<template>
  <a-modal
    v-model:open="open"
    title="上传你心爱的照片吧"
    width="50%"
    draggable
    :maskClosable="false"
    @cancel="handleCancel"
    @ok="handleOK"
  >
    <a-form
      ref="ruleFormRef"
      label-width="120px"
      class="demo-ruleForm"
      :model="ruleForm"
      size="default"
      status-icon
    >
      <a-form-item
        label="标签类型："
        name="tag"
        :rules="[{ required: true, message: '请输入标签类型', trigger: 'blur' }]"
      >
        <a-select
          style="width: 100%"
          placeholder="请输入标签类型"
          v-model:value="ruleForm.tag"
          :options="categoryOptions"
          allowClear
          mode="multiple"
          :max-tag-count="3"
        />
      </a-form-item>
      <a-form-item>
        <a-upload-dragger
          v-model:file-list="ruleForm.files"
          name="file"
          :multiple="true"
          :action="actionUrl"
          :auto-upload="false"
          :limit="10"
          :show-file-list="true"
          accept=".jpeg,.jpg,.png,.webp"
          @before-upload="beforeAvatarUpload"
        >
          <p class="ant-upload-drag-icon">
            <inbox-outlined></inbox-outlined>
          </p>
          <p class="ant-upload-text">拖拽文件或 <em>点击上传</em></p>
          <p class="ant-upload-hint">
            请上传大小不超过{{ ruleForm.limitSize
            }}{{ ruleForm.limitUnit }}的jpeg、jpg、png、webp格式的图片！
          </p>
        </a-upload-dragger>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { onBeforeUnmount, reactive, ref, unref } from 'vue'
import { type UploadProps, message } from 'ant-design-vue'
import { InboxOutlined } from '@ant-design/icons-vue'
import { ipcApiRoute, httpPostForm } from '@/api/router'
import type { ICategory } from '@/types/category'
import { getElectronHttp, emitter } from '@/core'

// 定义emits
const emit = defineEmits(['callback'])

// 获取分类标签
let categoryOptions = ref<ICategory[]>([])
emitter.on('updateCategories', (categories) => {
  categoryOptions.value = (categories as ICategory[]).map((item) => {
    return {
      ...item,
      value: item.id,
    }
  })
})

onBeforeUnmount(() => {
  emitter.off('updateCategories')
})

// 图片上传
const actionUrl = ref('')
/**
 * 获取图片上传地址
 */
const getHost = () => {
  getElectronHttp().then((res: string) => {
    const uri = ipcApiRoute.addFile
    actionUrl.value = res + '/' + uri.split('.').join('/')
  })
}
getHost()

/**
 * 图片上传前
 * @param rawFile
 */
const beforeAvatarUpload: UploadProps['beforeUpload'] = (file) => {
  if (!['image/jpeg', 'image/jpg', 'image/png'].includes(file.type)) {
    message.error('请上传jpeg、jpg、png格式的图片！')
    return false
  } else if (file.size / 1024 / 1024 > ruleForm.limitSize) {
    message.error(`图片大小不能超过${ruleForm.limitSize}${ruleForm.limitUnit}！`)
    console.log(`图片${file.uid}的大小为${file.size / 1024 / 1024}${ruleForm.limitUnit}`)
    return false
  }
  return true
}

// 表单相关
const ruleFormRef = ref()
const ruleForm = reactive({
  tag: [],
  files: [],
  limitSize: 20,
  limitUnit: 'MB',
})

// 弹窗相关
const open = ref(false)
/**
 * 打开弹窗
 */
const handleOpen = () => {
  open.value = true
}
/**
 * 取消弹窗
 */
const handleCancel = () => {
  ruleForm.tag = []
  ruleForm.files = []
  open.value = false
}
/**
 * 确认弹窗
 * @param formEl
 */
const handleOK = async () => {
  await unref(ruleFormRef).validate()

  if (!ruleForm.files.length) {
    message.error('请上传图片！')
    return
  }

  let formData = new FormData()
  ruleForm.files.forEach((file: any) => {
    formData.append('file', file.originFileObj)
  })
  formData.append('tags', ruleForm.tag.toString())
  httpPostForm(actionUrl.value, formData).then((res: any) => {
    if (res.code === 200) {
      message.success(res.message)
      emit('callback')
      handleCancel()
    } else {
      message.error(res.message)
    }
  })
}

defineExpose({ handleOpen })
</script>

<style scoped lang="less"></style>
